package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.contant.Contants;

import java.io.IOException;

/**
 * rpc 服务端
 * 1.接受请求
 * 2.发送响应5
 */

public class RpcServer {
    public static void main(String[] args) throws Exception{
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Contants.HOST);
        connectionFactory.setPort(Contants.PORT);
        connectionFactory.setUsername(Contants.USER_NAME);
        connectionFactory.setPassword(Contants.PASSWORD);
        connectionFactory.setVirtualHost(Contants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2.开启信道
        Channel channel = connection.createChannel();

        // 3.接受请求
        channel.basicQos(1); // 一次只能接收一条信息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body,"UTF-8");
                System.out.println("接收到请求: "+request);
                String response = "针对request: "+request+" 响应成功";
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",Contants.RPC_RESPONSE_QUEUE,basicProperties,response.getBytes());
                // getDeliveryTag:开启手动确认会生成,明确确认的信息是哪一条  false -> 不设置批量确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Contants.RPC_REQUEST_QUEUE,false,consumer);
    }
}
